import { ChatHistory } from '@/renderer/model/chat/db/ChatHistory';
import { ChatHistoryManager } from '@/renderer/service/manager/chat/ChatHistoryManager';
import { buildId } from '@/shared/utils/StringUtil';
import { ChatModel } from '@/renderer/model/chat/ChatMessage';
import { chatFileStoreService } from '@/renderer/service/chat/ChatFileStoreService';
import { chatMsgStorageService } from '@/renderer/service/chat/ChatMsgStorageService';
// const chatHistoryManager = new ChatHistoryManager();
export class ChatStorageService {
    private static instance: ChatStorageService;
     private chatHistoryManager: ChatHistoryManager;
 
      /**
   * 获取单例实例
   */
    public static getInstance(): ChatStorageService {
        if (!ChatStorageService.instance) {
        ChatStorageService.instance = new ChatStorageService();
        }
        return ChatStorageService.instance;
    }
    private constructor() {
        this.chatHistoryManager = new ChatHistoryManager();
    }
    // 创建聊天会话
    async createChatHistory(history: Omit<ChatHistory, 'id'|'create_time'|'update_time'>): Promise<number> {
        return await this.chatHistoryManager.createChatHistory(history);

    }

    // 创建聊天会话
    async createChat(chat_name: string): Promise<ChatModel|null> {
        const chat_id = buildId()
        const chat:ChatHistory = {
            id:0,
            chat_id : chat_id,
            chat_name: chat_name,
            create_time: '',
            update_time: '',
        }
        await this.chatHistoryManager.createChatHistory(chat);
        const result = await this.chatHistoryManager.getChatHistoryByChatId(chat_id)
        if(null == result){
            return null
        }
        return {
            id: result.chat_id,
            label: result.chat_name
        }
    }
    // 获取聊天会话分页列表
    async getChatHistoryPage(chatName:string, page = 1, pageSize = 20): Promise<ChatModel[]> {
        const result = await this.chatHistoryManager.getChatHistoryPage(chatName, page, pageSize);
        return result.map(item => {
            return {
                id: item.chat_id,
                label: item.chat_name
            }
        })
    }

    // 获取聊天会话总数
    async getChatHistoryTotalCount(): Promise<number> {
        return this.chatHistoryManager.getChatHistoryTotalCount();
    }
 
 
    
    // 更新聊天会话名称
    async updateChatHistoryName(chatId: string, chatName: string): Promise<boolean> {
        return this.chatHistoryManager.updateChatHistoryName(chatId, chatName);
    }
    // 删除聊天会话
    async deleteChatHistory(chatId: string): Promise<boolean> {
        await chatMsgStorageService.clearChatMessages(chatId)
        await chatFileStoreService.deleteFilesByChatId(chatId)
        return this.chatHistoryManager.deleteChatHistory(chatId);
    }

    
}
export const chatStorageService = ChatStorageService.getInstance();